﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LogToFile;

namespace MyWpfApp
{
    public class MyViewModel : ObservableObject
    {
        private int count = 1;

        public int Count
        {
            get { return count; }
            set
            {
                SetProperty(ref count, value);
            }
        }

        public MyViewModel()
        {
            
        }
        //public ICommand BtnAddCommand
        //{
        //    get
        //    {
        //        return new RelayCommand(() =>
        //        {
        //            using (var db = new ProjectDataBase.ProjectDbContext())
        //            {
        //                Count++;
        //                var item = db.TestDatas.FirstOrDefault();
        //                if (item == null)
        //                {
        //                    item = new ProjectDataBase.TestData()
        //                    {
        //                        ID = Guid.NewGuid(),
        //                        Data = 0
        //                    };
        //                    db.TestDatas.Add(item);
        //                    db.SaveChanges();
        //                }
        //                else
        //                {
        //                    item.Data = Count;
        //                    db.SaveChanges();
        //                }                        
        //            }

        //        });
        //    }
        //}

        public ICommand BtnAddCommand
        {
            get
            {
                return new RelayCommand(async () =>
                {
                    using (var db = new ProjectDataBase.ProjectDbContext())
                    {
                        Count++;
                        var item = await db.TestDatas.FirstOrDefaultAsync();
                        if (item == null)
                        {
                            item = new ProjectDataBase.TestData()
                            {
                                ID = Guid.NewGuid(),
                                Data = 0
                            };
                            db.TestDatas.Add(item);
                            await db.SaveChangesAsync();
                        }
                        else
                        {
                            item.Data = Count;
                            await db.SaveChangesAsync();
                            PLCLog.Info($"点击次数为：{Count}");
                        }
                    }
                });
            }
        }
    }
}
